using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace Project04
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        InputListener inputListener;
        SpriteFont spriteFont;

        //3D world
        private BasicEffect basicEffect;
        private Matrix world, view, projection;        
        private float fov, aspectRatio;
        private float rotation;

        //Grid
        private Grid grid;

        //Objects
        private Object gun, target, projectile;
        private Vector3 range;

        //Physics data
        private float velocity;
        private float timer;
        private float alpha1, alpha2;
        private float gamma;
        private const float g = 9.81f;

        //Output string
        private string infoString;
        private Vector2 infoPosition;

        //Handle input
        private bool isStart;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";

            graphics.PreferredBackBufferWidth = 1280;
            graphics.PreferredBackBufferHeight = 720;
            this.IsMouseVisible = true;
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here
            inputListener = new InputListener(this);
            Components.Add(inputListener);

            //3D World
            basicEffect = new BasicEffect(GraphicsDevice);

            aspectRatio = (float)graphics.GraphicsDevice.Viewport.Width / (float)graphics.GraphicsDevice.Viewport.Height;
            fov = MathHelper.PiOver4 * aspectRatio;
            rotation = 0f;

            world = Matrix.Identity;
            projection = Matrix.CreatePerspectiveFieldOfView(fov, aspectRatio, 1f, 1000f);

            //Grid
            grid = new Grid();

            //Object
            gun = new Object(new Vector3(-400, 0, -100));
            target = new Object(new Vector3(400,0,0));
            projectile = new Object(new Vector3(-400, 0, -100));
            range = new Vector3(800, 0, 100);

            //Physics data
            velocity = 100f;
            timer = 0f;

            //Output string
            infoPosition = new Vector2(950, 50);

            //Handle input
            isStart = false;

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);
            spriteFont = Content.Load<SpriteFont>("font");

            // TODO: use this.Content to load your game content here
            grid.LoadVertices();
            gun.LoadVertecies(Color.DarkGreen);
            target.LoadVertecies(Color.DarkRed);
            projectile.LoadVertecies(Color.Blue);
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (inputListener.isKeyDown(Keys.Escape))
                this.Exit();

            //Update camera rotation
            //if (inputListener.isKeyDown(Keys.Left))
            //    rotation += 0.02f;
            //if (inputListener.isKeyDown(Keys.Right))
            //    rotation -= 0.02f;
            
            rotation = (float)(0.0002 * gameTime.TotalGameTime.TotalMilliseconds);

            view = Matrix.CreateLookAt(new Vector3(500 * (float)Math.Sin(rotation), 400, 500 * (float)Math.Cos(rotation)),
                Vector3.Zero, Vector3.Up);

            //Handle input
            if (inputListener.isKeyPressed(Keys.Space))
                isStart = !isStart;

            if (inputListener.isKeyPressed(Keys.Back))
            {
                isStart = false;
                timer = 0;
                projectile.Vertices.RemoveRange(4, projectile.Vertices.Count - 4);
            }

            if (isStart == false && timer == 0)
            {
                //Adjust target position
                target.UpdatePosition(inputListener);
                range.X = Math.Abs(gun.Position.X) + Math.Abs(target.Position.X);
                range.Z = Math.Abs(gun.Position.Z - target.Position.Z);

                if (inputListener.isKeyPressed(Keys.Up) && velocity < 200)
                    velocity += 10f;
                if (inputListener.isKeyPressed(Keys.Down) && velocity > 100)
                    velocity -= 10f;
                
            }

            if (isStart == true)
            {
                timer += (float)gameTime.ElapsedGameTime.TotalSeconds;
                projectile.LoadLineStrip(projectile.Position, Color.Blue);
            }

            //Physics data
            alpha1 = (float)Math.Asin(g * Math.Sqrt(range.X * range.X + range.Z * range.Z) / (velocity * velocity)) / 2;
            alpha2 = MathHelper.PiOver2 - alpha1;
            gamma = (float)Math.Acos(range.X / Math.Sqrt(range.X * range.X + range.Z * range.Z));
            //Projectile travel position
            float x = (float)(gun.Position.X + velocity * Math.Sin(alpha2) * Math.Cos(gamma) * timer);
            float y = (float)(gun.Position.Y + velocity * Math.Cos(alpha2) * timer - g*timer*timer/2);
            float z = (float)(gun.Position.Z + velocity * Math.Sin(alpha2) * Math.Sin(gamma) * timer);
            projectile.Position = new Vector3(x, y, z);

            if (projectile.Position.Y < 0 )            
                isStart = false;

            basicEffect.World = world;
            basicEffect.View = view;
            basicEffect.Projection = projection;
            basicEffect.VertexColorEnabled = true;

            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            // TODO: Add your drawing code here
            grid.Draw(GraphicsDevice, basicEffect);
            //gun.Draw(GraphicsDevice, basicEffect);
            target.Draw(GraphicsDevice, basicEffect);
            projectile.Draw(GraphicsDevice, basicEffect);

            //Output info
            spriteBatch.Begin();
            infoString = "Gun ( " + gun.Position.X.ToString("0") + " , " + gun.Position.Y.ToString("0") + " , " + gun.Position.Z.ToString("0") + " )";
            infoString += "\nProjectile ( " + projectile.Position.X.ToString("0") + " , " + (-projectile.Position.Y).ToString("0") + " , " + projectile.Position.Z.ToString("0") + " )";
            infoString += "\nTarget ( " + target.Position.X.ToString("0") + " , " + target.Position.Y.ToString("0") + " , " + target.Position.Z.ToString("0") + " )";
            infoString += "\nRange ( " + range.X.ToString("0") + " , " + range.Y.ToString("0") + " , " + range.Z.ToString("0") + " )";
            infoString += "\n\nCorrect Alpha: " + MathHelper.ToDegrees(alpha1).ToString("0.00") + "  |  " + MathHelper.ToDegrees(alpha2).ToString("0.00");
            infoString += "\nCorrect Gamma: " + MathHelper.ToDegrees(gamma).ToString("0.00");
            infoString += "\n\nTime: " + timer.ToString("0.0") + " s";
            infoString += "\nVelocity: " + velocity.ToString("0.0") + " m/s";

            spriteBatch.DrawString(spriteFont, infoString, infoPosition, Color.Black);
            spriteBatch.End();

            base.Draw(gameTime);
        }
    }
}
